#include "StdAfx.h"
#include "ConnManager.h"
#include "Factory.h"

CConnManager::CConnManager(void)
{
}

CConnManager::~CConnManager(void)
{
}

void CConnManager::AddConn(ConnPtr pConn)
{
	if(!pConn) return ;

	RecMutex::Lock lock(m_mutex);
	string connId = CFactory::Instance()->GetConnId(pConn->GetIP(),pConn->GetPort());

	map<string,ConnPtr>::iterator pos = m_conns.find(connId);
	if(pos != m_conns.end())
	{
		pos->second->Stop();
		pos->second->getThreadControl().join();
		m_conns.erase(pos);
	}

	m_conns[connId] = pConn;
	pConn->start();
}

void CConnManager::DelConn(const string& connId)
{
	RecMutex::Lock lock(m_mutex);

	map<string,ConnPtr>::iterator pos = m_conns.find(connId);
	if(pos != m_conns.end())
	{
		pos->second->Stop();
		pos->second->getThreadControl().join();
		m_conns.erase(pos);
	}
}

ConnPtr CConnManager::GetConn(const string& connId)
{
	RecMutex::Lock lock(m_mutex);

	map<string,ConnPtr>::const_iterator pos = m_conns.find(connId);
	if(pos != m_conns.end())
	{
		return pos->second;
	}else
	{
		return NULL;
	}
}



